package com.tamo.ppresta.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.tamo.ppresta.bean.GetMineInfoBean;
import com.tamo.ppresta.db.DaoMaster;
import com.tamo.ppresta.db.DaoSession;
import com.tamo.ppresta.db.GetMineInfoBeanDao;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 * @author yeyang
 * @name ppresta
 * @class name：com.tamo.ppresta.greendao
 * @class describe
 * @time 2023/1/2 15:00
 * @change
 * @chang time
 * @class describe
 */
public class DBManager {
    private final static String dbName = "ppresta_db";
    private static DBManager mInstance;
    private DaoMaster.DevOpenHelper openHelper;
    private Context context;

    public DBManager(Context context) {
        this.context = context;
        openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
    }

    /**
     * 获取单例引用
     *
     * @param context
     * @return
     */
    public static DBManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (DBManager.class) {
                if (mInstance == null) {
                    mInstance = new DBManager(context);
                }
            }
        }
        return mInstance;
    }

    /**
     * 获取可读数据库
     */
    private SQLiteDatabase getReadableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
        }
        SQLiteDatabase db = openHelper.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     */
    private SQLiteDatabase getWritableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
        }
        SQLiteDatabase db = openHelper.getWritableDatabase();
        return db;
    }

    /**
     * 插入一条 GetMineInfoBean 记录
     *
     * @param getMineInfoBean
     */
    public void insertUser(GetMineInfoBean getMineInfoBean) {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        GetMineInfoBeanDao getMineInfoBeanDao = daoSession.getGetMineInfoBeanDao();
        getMineInfoBeanDao.insert(getMineInfoBean);
    }

    /**
     * 查询用户列表   getMineInfoBean
     */
    public GetMineInfoBean queryMineInfoBean() {
        DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        GetMineInfoBeanDao getMineInfoBeanDao = daoSession.getGetMineInfoBeanDao();
//        QueryBuilder<GetMineInfoBean> getMineInfoBean = getMineInfoBeanDao.queryBuilder();
        QueryBuilder<GetMineInfoBean> getMineInfoBeanQueryBuilder = getMineInfoBeanDao.queryBuilder();
        return getMineInfoBeanQueryBuilder.unique();
    }
}